package com.situ.mall.order.util;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.teaopenapi.models.Config;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.situ.mall.base.util.URLUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * ClassName: SendMsgUtil
 * Package: com.situ.mall.order.util
 * Description:
 *
 * @Author Darling_达
 * @Create 2023-04-03 15:19
 * @Version 1.0
 */

public class SendMsgUtil {

    public static final String TEMPLATE_CODE = "SMS_275255494";
    private static final String SING_NAME = "居逸生活";
    private static final String ERROR_MSG = "发送短信失败";

    public static void sendMsg(String tel, String code) throws Exception {
        Client client = createClient();
        SendSmsRequest sendSmsRequest = new SendSmsRequest();
        sendSmsRequest.setPhoneNumbers(tel);
        sendSmsRequest.setTemplateCode(TEMPLATE_CODE);
        sendSmsRequest.setSignName(SING_NAME);
        Map<String, String> map = new HashMap<>();
        map.put(URLUtil.CODE, code);
        SendSmsRequest request = sendSmsRequest.setTemplateParam(new ObjectMapper().writeValueAsString(map));
        try {
            client.sendSms(sendSmsRequest);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(ERROR_MSG);
        }
    }

    private static final String ACCESS_KEY_ID = "LTAI5tP9RfoN6G5zEgfAHjD4";
    private static final String ACCESS_KEY_SECRET = "qCHp5XNuU20vzPC84b2GYq0LrZ05cg";
    private static final String END_POINT = "dysmsapi.aliyuncs.com";

    /**
     * 使用AK&SK初始化账号Client
     *
     * @return Client
     */
    private static Client createClient() throws Exception {
        Config config = new Config()
                .setAccessKeyId(ACCESS_KEY_ID)  // 必填，您的 AccessKey ID
                .setAccessKeySecret(ACCESS_KEY_SECRET); // 必填，您的 AccessKey Secret
        config.endpoint = END_POINT; // 访问的域名
        return new Client(config);
    }

    /**
     * @return 随机生成  4 位 数字验证码
     */
    public static String createCode() {
        StringBuilder codes = new StringBuilder();
        Random r = new Random();
        // 2.定义一个for循环，随机n次，随机生成字符
        for (int i = 0; i < 4; i++) {
            // 3.生成随机数字
            codes.append(r.nextInt(10));
        }
        return codes.toString();
    }


}
